import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { SupplierPriceService } from './../../../@core/services/supplierPrice/supplier-price.service';
import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { DataTableComponent, DialogService, TableWidthConfig, TreeComponent } from 'ng-devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { SupplierService } from 'src/app/@core/services/supplier/supplier.service';
@Component({
  selector: 'app-supplier-price',
  templateUrl: './supplier-price.component.html',
  styleUrls: ['./supplier-price.component.scss']
})
export class SupplierPriceComponent {
  displayTreeData: any[] = []
  supplierTypeId: any;
  msgs: Array<Object> = [];
  option: any;
  filter = {
    SupplyClassId: null,
    PageSize: 20,
    PageNumber: 1,
    SearchTerm: null,
    SearchStatus: null
  }
  statusoptions = [
    '待审核','审核通过', '审核未通过'
  ]
  pathPids = []//树结构路径
  config = {
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  treeData: any = [
  ]
  tabledata = []
  pageSizeOptions = [10, 20, 30, 50, 100];
  pager = {
    total: 1
  }
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '价格表编码',
        fieldType: 'text',
        fixedLeft: '150px'
      },
      {
        field: 'code',
        header: '价格表名称',
        fieldType: 'text',
        fixedLeft: '300px'
      },
      {
        field: 'code',
        header: '供应商编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '供应商名称',
        fieldType: 'text',
      },
      {
        field: 'workCode',
        header: '供应商简称',
        fieldType: 'text'
      },
      {
        field: 'workCode',
        header: '状态',
        fieldType: 'text'
      },
      {
        field: 'workCode',
        header: '备注',
        fieldType: 'text'
      },
      {
        field: 'workCode',
        header: '创建时间',
        fieldType: 'text'
      },
      {
        field: 'workCode',
        header: '创建人',
        fieldType: 'text',
      }
    ]
  };//表头数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '40px'
    },
    {
      field: '操作',
      width: '110px'
    },
    {
      field: '价格表编码',
      width: '150px'
    },
    {
      field: '价格表名称',
      width: '150px'
    },
    {
      field: '供应商编码',
      width: '150px'
    },
    {
      field: '供应商名称',
      width: '200px'
    },
    {
      field: '供应商简称',
      width: '150px'
    },
    {
      field: '状态',
      width: '150px'
    },
    {
      field: '备注',
      width: '150px'
    },
    {
      field: '创建时间',
      width: '160px'
    },
    {
      field: '创建人',
      width: '150px'
    }
  ];//表格宽度配置
  dataTableOptions2 = {
    columns: [
      {
        field: 'code',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: 'code',
        header: '物料名称',
        fieldType: 'text',
      },
      {
        field: 'code',
        header: '物料规格',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料单位',
        fieldType: 'text',
      },
      {
        field: 'workCode',
        header: '价格',
        fieldType: 'text'
      },
      {
        field: 'workCode',
        header: '是否有效',
        fieldType: 'text'
      },
      {
        field: 'workCode',
        header: '生效日期',
        fieldType: 'text'
      },
      {
        field: 'workCode',
        header: '失效日期',
        fieldType: 'text'
      }
    ]
  };//表头数据
  tableWidthConfig2: TableWidthConfig[] = [
    {
      field: '物料编码',
      width: '150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '物料规格',
      width: '150px'
    },
    {
      field: '物料单位',
      width: '150px'
    },
    {
      field: '价格',
      width: '150px'
    },
    {
      field: '是否有效',
      width: '150px'
    },
    {
      field: '生效日期',
      width: '150px'
    },
    {
      field: '失效日期',
      width: '150px'
    }
  ];//表格宽度配置
  searchValue: any;
  @ViewChild('fileInput') fileInput: any;
  filteredTreeNodes: any[];
  @ViewChild('basicTree', { static: true }) basicTree!: TreeComponent;
  @ViewChild(DataTableComponent, { static: true }) datatable!: DataTableComponent;
  checkedIds: any = []
  file: any;
  filter2 = {
    PageSize: 20,
    PageNumber: 1,
    SearchTerm: "",
    SupplyId: null,
    SearchStatus: ""
  }
  partDetail: any = []
  partDetailHeight = '100%'
  splitBarSize = '0px'
  constructor(private SupplierService: SupplierService, private dialogService: DialogService, private SharedMethodService: SharedMethodService, private router: Router, private SupplierPriceService: SupplierPriceService) { }
  ngOnInit() {
    this.SupplierService.getSupplier(this.filter).subscribe((res: any) => {
      this.treeData = res.items
      this.displayTreeData = [{ supplyChineseName: '全部', supplyId: null }, ...this.treeData]
    })

    this.search()
  }
  afterTreeInit($event: any) {
    if ($event && Object.keys($event).length > 0) {
      if ($event.null) {
        $event.null.data.isActive = true
      }
    }
  }//树形菜单初始化
  nodeSelected($event: any) {
    this.option = $event.data.originItem
    this.supplierTypeId = $event.data.originItem.supplyId;
    this.filter2.SupplyId = this.supplierTypeId
    this.search()
    this.pathPids = this.getPathPids(this.option, this.treeData);// 输出路径 PID
  }
  searchClass($event: any) {
    this.searchValue = $event.target.value
    if (this.searchValue === '' || this.searchValue === null) {
      this.displayTreeData = [{ supplyChineseName: '全部', supplyId: null }, ...this.treeData]
    } else {
      this.filteredTreeNodes = this.filterCategories(this.treeData, this.searchValue);
      this.displayTreeData = this.filteredTreeNodes;
      this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
    }
  }//搜索树形菜单
  getPathPids(node: any, nodes: any[]) {
    for (let item of nodes) {
      let path = this.traverse(item, node.supplyClassId)
      if (path) {
        return path
      }
    }
    return null
  }//获取树形菜单pid的路径
  traverse(node: any, id: any, path = []) {
    path.push(node.supplyClassId);
    if (node.supplyClassId === id) {
      return path;
    }
    for (let child of node.subSupplyClasses) {
      let result = this.traverse(child, id, [...path]);
      if (result) {
        return result;
      }
    }
    return null;
  }//获取树形菜单pid的路径
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  filterCategories(categories: any[], keyword: string): any[] {
    const result: any[] = [];
    for (const category of categories) {
      if (category.supplyChineseName.includes(keyword)) {
        result.push(category);
      }
      if (category.subSupplyClasses?.length > 0) {
        const filteredSubCategories = this.filterCategories(category.subSupplyClasses, keyword);
        if (filteredSubCategories.length > 0) {
          result.push(...filteredSubCategories);
        }
      }
    }
    return result;
  }
  setOpenTrue = (node: any) => {
    // 为当前节点添加 open: true 属性
    node.open = true;
    // 如果当前节点有子节点，递归处理子节点
    if (Array.isArray(node.subSupplyClasses)) {
      node.subSupplyClasses = node.subSupplyClasses.map(this.setOpenTrue);
    }
    return node;
  }
  search() {
    this.SupplierPriceService.getSupplierPrice(this.filter2).subscribe((res: any) => {
      this.tabledata = res.items
      this.pager.total = res.totalCount
    })
  }
  search2() {
    this.filter2.PageNumber = 1
    this.SupplierPriceService.getSupplierPrice(this.filter2).subscribe((res: any) => {
      this.tabledata = res.items
      this.pager.total = res.totalCount
    })
  }
  reset() {
    this.filter2 = {
      PageSize: 20,
      PageNumber: 1,
      SearchTerm: "",
      SupplyId: null,
      SearchStatus: ""
    }
    this.search()
  }
  addSupplier() {
    this.router.navigate(['/pages/basicdata/supplier-price/supplier-price-add'])
  }
  editSupplier(id: any) {
    this.router.navigate(['/pages/basicdata/supplier-price/supplier-price-edit', id])
  }
  disApproval(id?: any) {
    this.SupplierPriceService.auditSupplierPrice('审核未通过',this.checkedIds).subscribe((res: any) => {
      this.showToast('success', '成功', '审核成功')
      this.checkedIds = []
      this.search()
    }),(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  }
  Approval(id?: any) {
    this.SupplierPriceService.auditSupplierPrice('审核通过',this.checkedIds).subscribe((res: any) => {
      this.showToast('success', '成功', '审核成功')
      this.search()
      this.checkedIds = []
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
    )
  }
  reverseApprove(id?:any){
    this.SupplierPriceService.auditSupplierPrice('待审核',this.checkedIds).subscribe((res: any) => {
      this.showToast('success', '成功', '反审核成功')
      this.search()
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
    )
  }
  deleteSupplier(id?: any, dialogtype?: string) {
    const results = this.dialogService.open({
      ...this.config,
      title: '删除',
      content: '确认删除该供应商价格表？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (id) {
              this.SupplierPriceService.deleteSupplierPrice([id]).subscribe((res: any) => {
                this.showToast('success', '成功', '删除成功')
                this.search()
                this.partDetail = []
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
              )
            }else {
              this.SupplierPriceService.deleteSupplierPrice(this.checkedIds).subscribe((res: any) => {
                this.showToast('success', '成功', '删除成功')
                this.search()
                this.partDetail = []
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
              )
            }
            results.modalInstance.hide()
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          }
        }
      ]
    });
  }
  pageIndexChange() {
    this.search()
  }
  pageSizeChange() {
    this.search()
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem, this.datatable)
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable, 'purchasePriceScheduleId').subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//获取选中行
  cleared() {
    this.SharedMethodService.cleared(this.checkedIds, this.tabledata, this.datatable).subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//清空选中行
  onFileSelected(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.SupplierPriceService.importExcel(this.file).subscribe((data: any) => {
      this.showToast('success', '成功', '导入成功')
      this.search()
      this.fileInput.nativeElement.value = ''
    },
    (error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//导入员工
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput.nativeElement.click();
  }
  DownloadSupplierFileModel() {
    this.SupplierPriceService.downloadExcel().subscribe((data: any) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '供应商价格表信息模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl)
    })
  }
  DownloadSupplierFile() {
    this.SupplierPriceService.uploadExcel().subscribe((data: any) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '供应商价格表信息.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }
  showDetail(data: any) {
    this.partDetail = data.purchasePriceScheduleParts,
      this.partDetailHeight = '75%',
      this.splitBarSize = '10px'
  }
}
